import subprocess
import _thread, tail
import hashlib
import platform
import os
import sys
import socket

def call_command(cmd):
    print("call_command ", cmd)
    code = os.system(cmd)
    if code != 0:
        print('call_command failed! ', cmd, " code:", code)
        return False
    return True


def adb_shell(cmd):
    print("adb_shell ", cmd)
    res = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # stdot, stderr = res.communicate()
    # code = res.returncode
    # print("stdot", stdot)
    # print("stderr", stderr)
    # print("code", code)
    result = res.stdout.read()
    res.wait()
    res.stdout.close()
    result = result.decode('utf-8')
    print('result ', result)
    return result


def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip
def get_host_ip2():
    host_name = socket.gethostname()
    ip = socket.gethostbyname(host_name)
    ip_ex = socket.gethostbyname_ex(host_name)
    print("主机名:", host_name)
    print("电脑ip:", ip, ip_ex)
    
    for i in ip_ex[-1]:
        if '172.' in i:
            local_ip = i
    print("内网IP：", local_ip)
    print("\n")

def log_device():
    print("\n电脑信息...")
    if sys.platform == "win32":
        print("操作系统:Windows")
    if sys.platform == "darwin":
        print("操作系统:mac")
    print("操作系统:", platform.architecture())
    print("机器类型:", platform.machine())
    print("网络名称:", platform.node())
    print("处理器名称:", end="")
    print(platform.processor())

    local_ip = get_host_ip()
    if local_ip is None:
        local_ip = "127.0.0.1"
    print("get_host_ip内网IP：", local_ip)
    print("\n")
    return local_ip


def tail_file(file):
    _thread.start_new_thread(tail_thread, (file,))


def read_file(file_path):
    if not os.path.isfile(file_path):
        return None
    f = open(file_path, "r")
    text = f.read()
    f.close()
    return text


def write_file(file_path, context):
    rmFile(file_path)
    f = open(file_path, "w", encoding='utf-8')
    f.write(context)
    f.close()


def tail_thread(tail_file):
    def unity_log_tail(txt):
        print(txt)

    print("wait for tail file ...", tail_file)
    while True:
        if os.path.exists(tail_file):
            print("Start tail file..... %s", tail_file)
            break
    t = tail.Tail(tail_file)
    t.register_callback(unity_log_tail)
    t.follow(s=1)


import shutil


def create_dir(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)


# 拷贝目录【类似unix下的cp -r aa bb】
def copyDir(srcDir, dstDir):
    if os.path.exists(srcDir):
        __copyDir(srcDir, dstDir)
    else:
        print(srcDir + ' not exist')


def __copyDir(srcDir, dstDir):
    if not os.path.exists(dstDir):
        shutil.copytree(srcDir, dstDir)
        return
    create_dir(dstDir)
    lists = os.listdir(srcDir)
    for lt in lists:
        srcPath = os.path.join(srcDir, lt)
        goalPath = os.path.join(dstDir, lt)
        if os.path.isfile(srcPath):
            shutil.copyfile(srcPath, goalPath)
        else:
            __copyDir(srcPath, goalPath)


# 拷贝目录下指定类型文件【类似unix下的cp aa/*.xx bb】
def copyDirExtFiles(srcDir, dstDir, ext, recursion=False):
    if os.path.exists(srcDir):
        __copyDirExtFiles(srcDir, dstDir, ext, recursion)
    else:
        print(srcDir + ' not exist')


def __copyDirExtFiles(srcDir, dstDir, ext, recursion=False):
    if not os.path.exists(dstDir):
        os.mkdir(dstDir)
    lists = os.listdir(srcDir)
    for lt in lists:
        srcPath = os.path.join(srcDir, lt)
        goalPath = os.path.join(dstDir, lt)
        if os.path.isfile(srcPath):
            tu = os.path.splitext(srcPath)
            if tu[1] == ext:
                shutil.copyfile(srcPath, goalPath)
        elif recursion == True:
            __copyDirExtFiles(srcPath, goalPath, ext, recursion)


# 删除文件夹下指定类型文件【类型unix下的 rm aa/*.xx】
def delExtFiles(srcDir, ext, recursion=False):
    lists = os.listdir(srcDir)
    for lt in lists:
        srcPath = os.path.join(srcDir, lt)
        if os.path.isfile(srcPath):
            tu = os.path.splitext(lt)
            if tu[1] == ext:
                os.remove(srcPath)
        elif recursion == True:
            delExtFiles(srcPath, ext, recursion)


# 删除文件夹下所有文件【类似unix下的 rm -r aa/bb】
def rmDirAllFiles(dstDir):
    if not os.path.isdir(dstDir):
        return
    lists = os.listdir(dstDir)
    for lt in lists:
        srcPath = os.path.join(dstDir, lt)
        if os.path.isfile(srcPath):
            os.remove(srcPath)
        else:
            shutil.rmtree(srcPath)


# 复制文件
def copyFile(srcFile, dstFile):
    if os.path.isfile(srcFile):
        shutil.copyfile(srcFile, dstFile)


# 复制文件到指定目录【类似unix下 cp .xx bb】
def copyFileToDir(srcFile, dstDir):
    if os.path.isfile(srcFile):
        tu = os.path.split(srcFile)
        copyFile(srcFile, os.path.join(dstDir, tu[1]))


# 删除文件【类似unix下 rm aa.xx】
def rmFile(fullPath):
    if os.path.isfile(fullPath):
        os.remove(fullPath)

#get_host_ip()
# build_dir = "/Users/meta/Projects/Meta-Art-VR-New-Jenkins-Win/AssetBundles/BuildVR/Win/3.0.0/1"
# work_dir = "/Volumes/samba/Jenkins/Meta彼岸/VR_Win_New_AB_20230113/2023_01_13_16_38_44_3.0.0_1/Win"
# create_dir(work_dir)
# copyDir(build_dir, work_dir)

